package biz

import (
	"New-lesson-part2/custom_error"
	"New-lesson-part2/internal"
	"New-lesson-part2/model"
	"New-lesson-part2/proto/pb"
	"context"
	"errors"
	"github.com/golang/protobuf/ptypes/empty"
)

// Brand 品牌相关操作

func (p ProductServer) CreateBrand(ctx context.Context, req *pb.BrandItemReq) (*pb.BrandItemRes, error) {
	var brand model.Brand
	r := internal.DB.Find("name = ? and logo = ?", req.Name, req.Logo)
	if r.RowsAffected > 0 {
		return nil, errors.New(custom_error.BrandAlreadyExits)
	}
	brand.Name = req.Name
	brand.Logo = req.Logo
	internal.DB.Save(&brand)
	res := ConvertBrandModel2pb(brand)
	return res, nil
}

func (p ProductServer) BrandList(ctx context.Context, req *pb.BrandPangingReq) (*pb.BrandRes, error) {

	var brandList []model.Brand
	var brands []*pb.BrandItemRes
	var brandRes pb.BrandRes
	r := internal.DB.Scopes(internal.MyPaging(req.PageNo, req.PageSize))
	res := r.Find(&brandList)
	if res.RowsAffected < 1 {
		return nil, errors.New(custom_error.BrandDoesNotExist)
	}
	if r.Error != nil {
		return nil, errors.New(custom_error.BrandDatabaseQueryError)
	}
	for _, i := range brandList {
		brands = append(brands, ConvertBrandModel2pb(i))
	}
	var count int64
	internal.DB.Model(&model.Brand{}).Count(&count) //这里说明一下.这里使用的最终总行数是全局数据库查出来的count结果.而不是分页的结果
	//上面语句的意思表示查询出的对应数据表中的所有数据行总和是多少.然后写入到count变量中.这里.Count方法只能接受int64
	brandRes.ItemList = brands
	brandRes.Total = int32(count)
	return &brandRes, nil
}

func (p ProductServer) DeleteBrand(ctx context.Context, req *pb.DelBrandReq) (*empty.Empty, error) {
	r := internal.DB.Delete(&model.Brand{}, req.Id)
	if r.Error != nil {
		return nil, errors.New(custom_error.BrandDeleteFailed)
	}

	return &empty.Empty{}, nil
}

func (p ProductServer) UpdateBrand(ctx context.Context, req *pb.UpdateBrandReq) (*empty.Empty, error) {
	//产品经理定义的规则
	var brand model.Brand
	r := internal.DB.First(&brand, req.Id)
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.BrandDoesNotExist)
	}
	if r.Error != nil {
		return nil, errors.New(custom_error.BrandDatabaseQueryError)
	}
	if req.Name == "" || req.Logo == "" {
		return nil, errors.New(custom_error.ParameterError)
	}
	brand.Name = req.Name
	brand.Logo = req.Logo
	res := internal.DB.Updates(&brand)
	if res.Error != nil {
		return nil, errors.New(custom_error.BrandUpdateFiled)
	}
	return &empty.Empty{}, nil
}

func ConvertBrandModel2pb(item model.Brand) *pb.BrandItemRes {
	brand := &pb.BrandItemRes{
		Name: item.Name,
		Logo: item.Logo,
	}
	if item.ID > 0 {
		brand.Id = item.ID
	}
	return brand
}
